import {
  Component,
  Host,
  h,
  Element,
  Prop,
  Event,
  EventEmitter,
  Method,
  writeTask,
  ComponentInterface,
} from '@stencil/core';
import {
  attachComponent,
  ComponentRef,
  deepReady,
  detachComponent,
  dismiss,
  eventMethod,
  FrameworkDelegate,
  hidden,
  ModalElement,
  present,
  show,
} from '../../model-core';

/**
 * 组件挂载容器
 *
 * @author chitanda
 * @date 2021-05-13 15:05:56
 * @export
 * @class IBzComponentContainer
 * @implements {ModalElement}
 * @implements {ComponentInterface}
 */
@Component({
  tag: 'ibz-component-container',
})
export class IBzComponentContainer implements ModalElement, ComponentInterface {
  @Element()
  el: HTMLIbzComponentContainerElement;

  @Prop()
  keyboardClose: boolean;

  @Prop()
  overlayIndex: number;

  presented = false;

  @Event({ eventName: 'osModalDidDismiss' })
  didDismiss: EventEmitter<any>;

  @Prop()
  component: ComponentRef;

  @Prop()
  componentProps: Record<string, unknown> = {};

  usersElement: HTMLElement;

  @Prop()
  delegate?: FrameworkDelegate;

  @Method()
  async present(): Promise<void> {
    if (this.presented) {
      return;
    }

    if (this.component) {
      const componentProps = {
        ...this.componentProps,
        modal: this.el,
      };
      this.usersElement = await attachComponent(
        this.delegate,
        this.el,
        this.component,
        ['model-view-content'],
        componentProps,
      );
      await deepReady(this.usersElement);
      writeTask(() => show(this.el));
    } else {
      show(this.el);
    }
    present(this);
  }

  @Method()
  async dismiss(data?: any): Promise<boolean> {
    if (this.component) {
      await dismiss(this, data);
      await detachComponent(this.delegate, this.usersElement);
      // 初始化
      this.el.component = undefined;
      this.componentProps = {};
      writeTask(() => hidden(this.el));
    } else {
      hidden(this.el);
    }
    return true;
  }

  @Method()
  async onDidDismiss(): Promise<any> {
    return eventMethod(this.el, 'osModalDidDismiss');
  }

  render() {
    return <Host class='os-container ibz-component-container'></Host>;
  }
}
